package com.conversationboard.controller;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.conversationboard.cache.UserCache;
import com.conversationboard.database.Database;
import com.conversationboard.database.Queries;
import com.conversationboard.model.User;

@WebServlet(name = "AdminDeleteBanRequest", urlPatterns = "/Admin/AdminDeleteBanRequest")
public class AdminDeleteBanRequest extends HttpServlet {

	private static final long serialVersionUID = 4892048713432513347L;


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		try {

			User user = User.get(request.getUserPrincipal().getName());

			if (!user.isSiteAdmin()) {
				return;
			}

			if (!SecurityChecks.passes(request, user, this)) {
				return;
			}

			int id = Integer.parseInt(request.getParameter("id"));

			Connection connection = null;

			try {
				connection = Database.getConnection();

				PreparedStatement statement = connection.prepareStatement(Queries.REMOVE_SUGGEST_BAN);
				statement.setInt(1, id);

				statement.executeUpdate();
				statement.close();

			} finally {
				Database.close(connection);
			}

			/* Remove this user from the cache so their SB count is updated. */

			UserCache.getInstance().removeUser(request.getParameter("loginId"));

			RequestDispatcher dispatcher = request.getRequestDispatcher("/Admin/AdminViewBanRequestsControllerServlet");
			dispatcher.forward(request, response);

		} catch (SQLException e) {
			throw new ServletException(e);
		}

	}

}
